package com.wangjiang.mario.admin.system.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.wangjiang.mario.admin.common.base.BaseServiceImpl;
import com.wangjiang.mario.admin.common.exception.NoFoundException;
import com.wangjiang.mario.admin.common.util.CommonUtils;
import com.wangjiang.mario.admin.system.domain.components.ConfigComponent;
import com.wangjiang.mario.admin.system.domain.entity.SystemConfigEntity;
import com.wangjiang.mario.admin.system.domain.mapper.SystemConfigMapper;
import com.wangjiang.mario.admin.system.domain.service.SystemConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SystemConfigServiceImpl extends BaseServiceImpl<SystemConfigMapper, SystemConfigEntity>
        implements SystemConfigService {

    private static final Logger logger = LoggerFactory.getLogger(SystemConfigServiceImpl.class);

    @Autowired
    private ConfigComponent configComponent;

    /**
     * 根据key 查找实体
     * @param key
     * @return
     */
    @Override
    public SystemConfigEntity getByKey(String key) {
        Wrapper wrapper = getDefaultWrapper().eq("config_key", key);
        return getOne(wrapper);
    }

    /**
     * 保存之后做一下缓存
     * @param entity 实体对象
     * @return
     */
    @Override
    public boolean baseUpdateById(SystemConfigEntity entity) {
        boolean ret = super.baseUpdateById(entity);
        SystemConfigEntity nowEntity = baseGetByUUid(entity.getUuid());
        if(ret) {
            configComponent.cache(nowEntity.getConfigKey(), nowEntity.getConfigValue());
        }
        return ret;
    }

    @Override
    public String getValueByKey(String key) {
        SystemConfigEntity entity = getByKey(key);
        if(CommonUtils.isNotNull(entity))
            return entity.getConfigValue();
        else
            throw new NoFoundException("没有该key的配置");
    }
}
